package com.glela.platform.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.platform.mapper.BaseRestrictionsMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.service.BaseRestrictionsService;

@Service("baseRestrictionsService")
@Scope("singleton")
public class BaseRestrictionsServiceImpl implements BaseRestrictionsService {
	protected static Logger logger = LoggerFactory.getLogger(BaseRestrictionsServiceImpl.class);

	@Autowired
	private BaseRestrictionsMapper	baseRestrictionsMapper;
	@Autowired
	private RedisUtil				redisUtil;

	/**
	 * 根据类型查询限制信息
	 * 
	 * @param type
	 * @return
	 */
	@Override
	public BaseRestrictions selectAllBaseRestrictionsByType(String type) {
		// TODO Auto-generated method stub
		return baseRestrictionsMapper.selectAllBaseRestrictionsByType(type);
	}

	@Override
	public int selectCommisionLimit() {
		return baseRestrictionsMapper.selectCommisionLimit();
	}

	@Override
	public BaseRestrictions getBaseRestrictionsForCache(BaseRestrictionsEnum baseRestrictionsEnum) {
		return baseRestrictionsEnum == null ? null : getBaseRestrictionsForCache(baseRestrictionsEnum.getText());
	}

	@Override
	public BaseRestrictions getBaseRestrictionsForCache(String type) {
		if (StringUtils.isEmpty(type)) {
			return null;
		}
		String cacheValue = null;
		try {
			cacheValue = redisUtil.hget(RedisKeys.YG_SYSTEM_BASE_RESTRICTIONS, type);
		}catch (Exception e) {
			logger.error("查询REDIS错误: {}", e);
			cacheValue = null;
		}
		try {
			if (StringUtils.isBlank(cacheValue)) {
				BaseRestrictions baseRestrictions = selectAllBaseRestrictionsByType(type);
				if (baseRestrictions != null) {
					try {
						redisUtil.hmset(RedisKeys.YG_SYSTEM_BASE_RESTRICTIONS, type, JSONObject.toJSONString(baseRestrictions));
					}catch (Exception es) {
						logger.error("写入REDIS错误: {}", es);
					}
				}
				return baseRestrictions;
			} else {
				return JSON.parseObject(cacheValue, BaseRestrictions.class);
			}
		} catch (Exception e) {
			logger.error("类型转换错误	： {}", e.getMessage(), e);
			return null;
		}
	}
}